package cn.sinokj.party.chineseFourParty.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.ForgotPasswordActivity;
import cn.sinokj.party.chineseFourParty.activity.MainActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.LoginInfo;
import cn.sinokj.party.chineseFourParty.fragment.base.BaseFragment;
import cn.sinokj.party.chineseFourParty.jpush.utils.JPushUtil;
import cn.sinokj.party.chineseFourParty.service.HttpConstants.ReturnResult;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.Constans;
import cn.sinokj.party.chineseFourParty.utils.Utils;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmDialog;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmInterface;
import de.greenrobot.event.EventBus;

/**
 * Created by l on 2017/11/13.
 */

public class LoginFragment extends BaseFragment {
    private static final int LOGIN = 1;
    private static final int BIND_INFO = 2;
    /*@BindView(R.id.title)
    public TextView titleText;*/

    @BindView(R.id.login_username)
    public EditText usernameEdit;
    @BindView(R.id.login_password)
    public EditText passwordEdit;
    @BindView(R.id.login_forgot_password)
    public TextView forgotPasswdText;
    @BindView(R.id.status_bar_height)
    View statusBarHeight;
    Unbinder unbinder;
    private String username, password;
    private MainActivity activity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.login, container, false);
        unbinder = ButterKnife.bind(this, view);
        initImmersionBar(statusBarHeight);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (MainActivity) getActivity();

        //forgotPasswdText.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        SharedPreferences shared = activity.getSharedPreferences("user", Activity.MODE_PRIVATE);
        usernameEdit.setText(shared.getString("username", ""));
        passwordEdit.setText(shared.getString("password", ""));
    }

    @OnClick({R.id.login_login, R.id.login_forgot_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_login:
                if (initializeArgs()) {
                    DialogShow.showRoundProcessDialog(activity);
                    new Thread(new LoadDataThread(LOGIN)).start();
                }
                break;
            case R.id.login_forgot_password:
                Intent intent = new Intent();
                intent.setClass(activity, ForgotPasswordActivity.class);
                startActivity(intent);
                break;
        }
    }

    private boolean initializeArgs() {
        username = usernameEdit.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(activity, "请输入登陆账号", Toast.LENGTH_SHORT).show();
            return false;
        }
        password = passwordEdit.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(activity, "请输入登陆密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case LOGIN:
                return HttpDataService.login(username, password);
            case BIND_INFO:
                return HttpDataService.bindPushInfo(
                        JPushInterface.getRegistrationID(activity),
                        JPushUtil.getAppKey(activity.getApplicationContext()),
                        Utils.PLATFORM, Utils.DEVICE_TYPE);
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        DialogShow.closeDialog();
        switch (msg.what) {
            case LOGIN:
                if (jsonObject.optInt(ReturnResult.NRES) != 1) {
                    Toast.makeText(activity, jsonObject.optString(ReturnResult.VCRES), Toast.LENGTH_SHORT)
                            .show();
                    return;
                }

                App.loginStatus = true;
                // 存储帐号
                SharedPreferences shared = activity.getSharedPreferences("user", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = shared.edit();
                editor.putString("username", username);
                editor.putString("password", password);
                Gson gson = new Gson();
                String s = jsonObject.toString();
                LoginInfo loginInfo = gson.fromJson(s, LoginInfo.class);
                App.nCommitteeId = loginInfo.getnCommitteeId();
                App.loginInfo = loginInfo;
                App.MINE_REFRESH = true;
                editor.commit();

                new Thread(new LoadDataThread(BIND_INFO)).start();
                break;
            case BIND_INFO:
                /*if (jsonObject.optInt(ReturnResult.NRES) != 1) {
                    Toast.makeText(activity, jsonObject.optString(ReturnResult.VCRES), Toast.LENGTH_SHORT)
                            .show();
                    return;
                }*/
                //Set<String> tags = new HashSet<String>();
                //tags.add(String.valueOf(jsonObject.optInt("groupId", 0)));
                //mHandler.sendMessage(mHandler.obtainMessage(0, tags));
                finishLogin();
                break;
        }
    }

    private void finishLogin() {

        if (Utils.INITIAL_PASSWORD.equals(password)) {
            ConfirmDialog.confirmAction(activity, "请及时修改密码!", "确定", null, new ConfirmInterface() {
                @Override
                public void onOkButton() {
                    Message msg1 = Message.obtain();
                    msg1.what = Constans.SHOW_MINE;
                    EventBus.getDefault().post(msg1);

                    Message msg2 = Message.obtain();
                    msg2.what = Constans.MINE_REFRESH;
                    EventBus.getDefault().post(msg2);

                    Message msg3 = Message.obtain();
                    msg3.what = Constans.HOME_REFRESH;
                    EventBus.getDefault().post(msg3);

                    Message msg4 = Message.obtain();
                    msg4.what = Constans.ANNOUNCEMENT_REFRESH;
                    EventBus.getDefault().post(msg4);
                }

                @Override
                public void onCancelButton() {
                }

                @Override
                public void onDismiss(DialogInterface dialog) {

                }
            });
        } else {
            Message msg1 = Message.obtain();
            msg1.what = Constans.SHOW_MINE;
            EventBus.getDefault().post(msg1);
            Message msg2 = Message.obtain();
            msg2.what = Constans.MINE_REFRESH;
            EventBus.getDefault().post(msg2);
            Message msg3 = Message.obtain();
            msg3.what = Constans.HOME_REFRESH;
            EventBus.getDefault().post(msg3);
            Message msg4 = Message.obtain();
            msg4.what = Constans.ANNOUNCEMENT_REFRESH;
            EventBus.getDefault().post(msg4);
        }

    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            JPushInterface.setTags(activity.getApplicationContext(), (Set<String>) msg.obj, mTagsCallback);
        }
    };

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    logger.i(logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    logger.i(logs);
                    if (JPushUtil.isConnected(activity.getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(0, tags), 1000 * 60);
                    } else {
                        logger.i("No network");
                    }
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    logger.e(logs);
            }
//			JPushUtil.showToast(logs, getApplicationContext());
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
